package com.gk.carshopsys.controller;

import com.gk.carshopsys.dao.CarConfigMapper;
import com.gk.carshopsys.pojo.*;
import lombok.RequiredArgsConstructor;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@Controller
@RequestMapping("/car-config")
@RequiredArgsConstructor
public class CarConfigController {

    private final CarConfigMapper carConfigMapper;

    /* 步骤1：选择车系（展示所有车系） */
    @GetMapping
    public String seriesList(Model model) {
        model.addAttribute("seriesList", carConfigMapper.findAllSeries());
        return "car-config-series";  // templates/car-config-series.html
    }

    /* 步骤2：进入某车系的选配页（根据 seriesId 加载所有数据） */
    @GetMapping("/{seriesId}")
    public String configPage(@PathVariable Integer seriesId,
                             Model model) {
        List<CarModel> models   = carConfigMapper.findModelsBySeries(seriesId);
        List<CarColor>   colors   = carConfigMapper.findColorsBySeries(seriesId);
        List<CarInterior> interiors = carConfigMapper.findInteriorsBySeries(seriesId);
        List<CarOption>  options  = carConfigMapper.findOptionsBySeries(seriesId);


        // 当前车系“顶配”价格 = 最高车型 + 最贵颜色 + 最贵内饰 + 所有选装
        int maxModel   = models.stream().mapToInt(CarModel::getBasePrice).max().orElse(0);
        int maxColor   = colors.stream().mapToInt(CarColor::getExtraPrice).max().orElse(0);
        int maxInterior= interiors.stream().mapToInt(CarInterior::getExtraPrice).max().orElse(0);
        int maxOptions = options.stream().mapToInt(CarOption::getExtraPrice).sum();

        int maxPrice = maxModel + maxColor + maxInterior + maxOptions;

        model.addAttribute("models",   models);
        model.addAttribute("colors",   colors);
        model.addAttribute("interiors",interiors);
        model.addAttribute("options",  options);
        model.addAttribute("maxPrice", maxPrice);   // ← 传给页面
        return "car-config";  // templates/car-config.html
    }
}